package com.easy.security.filter;

import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.filter.OncePerRequestFilter;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class PermissionFilter extends OncePerRequestFilter {
    @Override
    protected void doFilterInternal(HttpServletRequest request,
                                    HttpServletResponse response,
                                    FilterChain filterChain) throws ServletException, IOException {
        // 从 Header 中读取权限字符串
        String permissionsHeader = request.getHeader("X-User-Permissions");
        if (permissionsHeader != null) {
            // 解析权限列表，例如 ["user:read", "order:write"]
            List<GrantedAuthority> authorities = Arrays.stream(permissionsHeader.split(","))
                    .map(permission -> new SimpleGrantedAuthority(permission.trim()))
                    .collect(Collectors.toList());
            // 构建 Authentication 对象（无需密码，故第二个参数为 null）
            Authentication authentication =
                    new UsernamePasswordAuthenticationToken("user", null, authorities);

            // 设置到 SecurityContext
            SecurityContextHolder.getContext().setAuthentication(authentication);
        }
        filterChain.doFilter(request, response);
    }
}
